require('@/app')
var CONST_MENUS = require('@/contabs.min')


/**
 * 1、回显菜单
 * 2、刷新iframe地址
 */
function reloadMain() {
    var hash = window.location.hash;
    if (hash && hash.length > 0) {
        var items = hash.substr(1, hash.length).split('#');
        if (items.length == 2) {
            var main_url = items[0];
            var m_id = items[1];
            $.cookie("m_id", m_id, { path: "/" });
            $("#main_iframe").attr('src', main_url + '#' + m_id);
        }
    } else {
        $.cookie('m_id', '', { path: "/", expires: -1 });
    }
}

/**
 * 检查登录
 */
function checkLogin() {
    $("#index_loading").show();
    /*var is_login = $.cookie("is_login");  //判断是否登录
    console.log('checkLogin', is_login)
    if (is_login != "true") {
        location.href = "login.html";
    } else {
        $("#index_loading").hide();
        $("#wrapper").show();
    }*/
    $("#index_loading").hide();
    $("#wrapper").show();
}

/**
 * 加载菜单
 */
function loadMenu() {
    // var accessToken = $.cookie("u_id") + "_" + $.cookie("tokenId");
    // $.ajax({
    //     url: '/sysUser/listUserMenu',
    //     type: "get",
    //     dataType: 'json',
    //     async: false,    //同步
    //     beforeSend: function (request) {
    //         request.setRequestHeader("AccessToken", accessToken);
    //     },
    //     success: function (data) {
    //         var sel_menu_id = $.cookie('m_id') || -9999;
    //         var third_menu = false;
    //         if (data.code == 1) {
    //             var menus = data.data;
    //             createMenus(menus);

    //             var sel_menu_id = $.cookie('m_id') || -9999;
    //             if (sel_menu_id > -9999) {
    //                 $("a.J_menuItem[data-menu-id=" + sel_menu_id + "]").css('color', '#FFF');
    //                 $("a.J_menuItem[data-menu-id=" + sel_menu_id + "]").parent().parent().parent().addClass('active');
    //                 if (third_menu) {
    //                     $("a.J_menuItem[data-menu-id=" + sel_menu_id + "]").parent().parent().parent().parent().parent().addClass('active');
    //                 }
    //             }
    //         } else {//请求失败
    //             location.href = "login.html";
    //         }
    //     }
    // });

    var menus = [
        {
            id: 1,
            iconCls: '',
            menuPath: 'views/home.html',
            menuName: '首页'
        },
        {
            id: 2,
            iconCls: '',
            menuPath: '',
            menuName: '系统页面',
            children: [
                {
                    id: 2001,
                    iconCls: '',
                    menuPath: 'views/404.html',
                    menuName: '404'
                },
                {
                    id: 2002,
                    iconCls: '',
                    menuPath: 'views/500.html',
                    menuName: '500'
                }
            ]
        },
        {
            id: 3,
            iconCls: '',
            menuPath: '',
            menuName: '控件元素',
            children: [
                {
                    id: 3001,
                    iconCls: '',
                    menuPath: 'views/date.html',
                    menuName: '日期'
                },
                {
                    id: 3002,
                    iconCls: '',
                    menuPath: '',
                    menuName: '图表',
                    children: [
                        {
                            id: 300201,
                            iconCls: '',
                            menuPath: 'views/linechart.html',
                            menuName: '线形图表'
                        },
                        {
                            id: 300202,
                            iconCls: '',
                            menuPath: 'views/piechart.html',
                            menuName: '饼图表'
                        },
                        {
                            id: 300203,
                            iconCls: '',
                            menuPath: 'views/radarchart.html',
                            menuName: '雷达图表'
                        }
                    ]
                },
                {
                    id: 3003,
                    iconCls: '',
                    menuPath: 'views/valid.html',
                    menuName: '表单验证'
                },
                {
                    id: 3004,
                    iconCls: '',
                    menuPath: 'views/datatable.html',
                    menuName: '表格验证'
                },
                {
                    id: 3005,
                    iconCls: '',
                    menuPath: 'views/dot.html',
                    menuName: '数据绑定'
                },
                {
                    id: 3006,
                    iconCls: '',
                    menuPath: 'views/multiselect.html',
                    menuName: '多选择绑定'
                }
                
            ]
        }
    ];
    createMenus(menus);

    
}

/**
 * 生成菜单
 * 
 * @param {any} menus 
 */
function createMenus(menus) {
    var sel_menu_id = $.cookie('m_id') || -9999;
    var third_menu = false;

    var length = menus.length;
    var menu_html = '';
    for (var i = 0; i < length; i++) {
        //支持三级菜单
        var menu = menus[i];
        if (menu.menuPath && menu.menuPath.length > 0 && (!menu.children || menu.children.length == 0)) {
            menu_html += "<li><a class=\"J_menuItem\" href=\"" + menu.menuPath + "#" + menu.id + "\" data-menu-id=\"" + menu.id + "\" ><i class=\"fa fa-" + menu.iconCls + "\"></i> <span class=\"nav-label\">" + menu.menuName + "</span></a></li>";
        } else {
            menu_html += "" +
                "<li>" +
                "     <a href=\"#\"><i class=\"fa fa-" + menu.iconCls + "\"></i> <span class=\"nav-label\">" + menu.menuName + "</span><span class=\"fa arrow\"></span></a>" +
                "     <ul class=\"nav nav-second-level\">";
            for (var n = 0; n < menu.children.length; n++) {
                var children = menu.children[n];
                if (children.menuPath && children.menuPath.length > 0 && (!children.children || children.children.length == 0)) {
                    menu_html += "<li><a class=\"J_menuItem\" href=\"" + children.menuPath + "#" + children.id + "\" data-menu-id=\"" + children.id + "\">" + children.menuName + "</a></li>";
                } else {
                    menu_html += "<li><a href=\"#\">" + children.menuName + "<span class=\"fa arrow\"></span></a>" +
                        "<ul class=\"nav nav-third-level\">";
                    if (children.children && children.children.length > 0) {
                        for (var m = 0; m < children.children.length; m++) {
                            var c = children.children[m];
                            menu_html += "<li><a class=\"J_menuItem\" href=\"" + c.menuPath + "#" + c.id + "\" data-menu-id=\"" + c.id + "\">" + c.menuName + "</a></li>";
                            if (sel_menu_id == c.id) {
                                third_menu = true;
                            }
                        }
                    }
                    menu_html += "" +
                        "    </ul>" +
                        " </li>";
                }
            }
            menu_html += "" +
                "    </ul>" +
                " </li>";
        }
    }
    $("#side-menu").append(menu_html);

    var sel_menu_id = $.cookie('m_id') || -9999;
    if (sel_menu_id > -9999) {
        $("a.J_menuItem[data-menu-id=" + sel_menu_id + "]").css('color', '#FFF');
        $("a.J_menuItem[data-menu-id=" + sel_menu_id + "]").parent().parent().parent().addClass('active');
        if (third_menu) {
            $("a.J_menuItem[data-menu-id=" + sel_menu_id + "]").parent().parent().parent().parent().parent().addClass('active');
        }
    }

    CONST_MENUS.init();
    // console.log(CONST_MENUS)
}

/**
 * 退出登录
 */
function logout() {
    $.dialog.confirm("提示", "确定要退出吗？", function () {
        var accessToken = $.cookie("u_id") + "_" + $.cookie("tokenId");
        $.ajax({
            url: '/sysUser/logout',
            type: "post",
            dataType: 'json',
            async: false,    //同步
            beforeSend: function (request) {
                request.setRequestHeader("AccessToken", accessToken);
            },
            success: function (data) {
                $.cookie('u_id', '', { path: "/", expires: -1 });
                //$.cookie('u_name', '', {path: "/", expires: -1});
                $.cookie('m_id', '', { path: "/", expires: -1 });
                location.href = "login.html";
            }
        });
    });
}

/**
 * 修改密码
 */
function edit_password() {
    getSession();
    password = EncryptX($("#txtOldPass").val());
    var uid = $.cookie("u_id");
    var accessToken = uid + "_" + $.cookie("tokenId");
    $.ajax({
        url: '/sysUser/updatePwd',
        type: "post",
        dataType: 'json',
        contentType: "application/json; charset=utf-8",
        data:
        JSON.stringify(
            {
                userId: uid,
                password: password,
                newPwd: $("#txtNewPass").val()
            }
        )
        ,
        beforeSend: function (request) {
            request.setRequestHeader("AccessToken", accessToken);
        },
        success: function (data) {
            if (data.code == 1) {
                //              $.cookie("is_login", "", {path: "/", expires: -1});
                //              $.cookie('m_id', '', {path: "/", expires: -1});
                $.cookie('u_id', '', { path: "/", expires: -1 });
                $.cookie('u_name', '', { path: "/", expires: -1 });
                $.dialog.alert("提示", "密码修改成功，请重新登录", "success", function () {
                    location.href = "login.html";
                });
            } else {
                $.dialog.alert("提示", data.msg, "error");
            }
            $("#modal_edit_password").modal('hide');
        },
        error: function (data) {
            $.dialog.alert("提示", data.msg, "error");
        }
    });
}


function getSession() {
    var accessToken = $.cookie("u_id") + "_" + $.cookie("tokenId");
    $.ajax({
        url: '/sysUser/getPwdKey',
        type: "post",
        dataType: 'json',
        async: false,    //同步
        data: {},
        beforeSend: function (request) {
            request.setRequestHeader("AccessToken", accessToken);
        },
        success: function (data) {
            $.cookie('pwd_key', data.data, { path: "/", expires: 60 * 1000 });
        }
    });
}

function EncryptX(word) {
    var key = CryptoJS.enc.Utf8.parse($.cookie('pwd_key'));
    var srcs = CryptoJS.enc.Utf8.parse(word);

    var encrypted = CryptoJS.AES.encrypt(srcs, key, { mode: CryptoJS.mode.ECB, padding: CryptoJS.pad.Pkcs7 });
    return encrypted.toString();
}


$(document).ready(function () {

    reloadMain();
    checkLogin();
    loadMenu();

    var user_name = $.cookie('u_name');
    $("#u_name").html(' ' + user_name + ' ');

    $(".logout").on('click', function () {
        logout();
    });

    $("#edit_password").on('click', function () {
        $("#modal_edit_password").modal('show');
    });

    $('#modal_edit_password').on('hide.bs.modal', function () {
        $("#txtOldPass").val('');
        $("#txtNewPass").val('');
        $("#txtRePass").val('');
        $('#fm_edit_password').bootstrapValidator('resetForm', true);
    });

    $(window).bind('hashchange', function () {
        window.location.reload();
    });

    $('#fm_edit_password').bootstrapValidator({
        feedbackIcons: {
            valid: 'glyphicon glyphicon-ok',
            invalid: 'glyphicon glyphicon-remove',
            validating: 'glyphicon glyphicon-refresh'
        },
        fields: {
            txtOldPass: {
                validators: {
                    notEmpty: {
                        message: '此项必填'
                    }
                }
            },
            txtNewPass: {
                validators: {
                    notEmpty: {
                        message: '此项必填'
                    }
                }
            },
            txtRePass: {
                validators: {
                    notEmpty: {
                        message: '此项必填'
                    },
                    callback: {
                        message: '两次密码不一致',
                        callback: function (value, validator) {
                            var new_pass = $('#txtNewPass').val();
                            return value == new_pass;
                        }
                    }
                }
            }
        }
    }).on('success.form.bv', function (e) {
        e.preventDefault();
        edit_password();
    });
});
